package com.system.core.dingtalk;

import java.net.URLEncoder;

import org.springframework.stereotype.Service;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.system.core.dingtalk.dto.TalkConfig;
import com.taobao.api.TaobaoObject;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

@Service
@AllArgsConstructor
public class DingTalkService {

	private final TalkConfig talkConfig;
	
	private DingRequest buildRequest(String configName,TaobaoObject taobaoObject) throws Exception {
		Long timestamp = System.currentTimeMillis();
		String signData = DingTalkUtil.getSign(timestamp, talkConfig.getConfigByName(configName).getSecret());
		String sign = URLEncoder.encode(signData,"UTF-8");
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign="+sign+"&timestamp="+timestamp);
        OapiRobotSendRequest req = new OapiRobotSendRequest();
        return DingRequest.builder().dingTalkClient(client).oapiRobotSendRequest(req).build();
	}
	
	public OapiRobotSendResponse talkText(String configName,String content) throws Exception {
		OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
		text.setContent(content);
		DingRequest dingRequest = buildRequest(configName,text);
		DingTalkClient client = dingRequest.getDingTalkClient();
		OapiRobotSendRequest req = dingRequest.getOapiRobotSendRequest();
		req.setMsgtype("text");
        req.setText(text);
        OapiRobotSendResponse rsp = client.execute(req, talkConfig.getConfigByName(configName).getCustomRobotToken());
        return rsp;
	}
	
	public OapiRobotSendResponse talkMarkDown(String configName,String title,String content) throws Exception {
		OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
		markdown.setTitle(title);
		markdown.setText(content);
		DingRequest dingRequest = buildRequest(configName,markdown);
		DingTalkClient client = dingRequest.getDingTalkClient();
		OapiRobotSendRequest req = dingRequest.getOapiRobotSendRequest();
		req.setMsgtype("markdown");
        req.setMarkdown(markdown);
        OapiRobotSendResponse rsp = client.execute(req, talkConfig.getConfigByName(configName).getCustomRobotToken());
        return rsp;
	}
	
	@Data
	@Builder
	public static class DingRequest{
		private DingTalkClient dingTalkClient;
		private OapiRobotSendRequest oapiRobotSendRequest;
	}
}
